package com.tma.basicfragment;

import java.util.List;

import a.thread.AsyncTaskWrapper;
import a.thread.AsyncTaskWrapper.AsyncTaskCallback;
import a.thread.TaskFragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.tma.basicfragment.CategoryFragment.OnCategorySelectedListener;
import com.tma.basicfragment.book.Book;
import com.tma.basicfragment.book.BookAdapter;
import com.tma.basicfragment.book.LoadBookResult;
import com.tma.basicfragment.book.LoadBookTask;
import com.tma.basicfragment.music.LoadSongResult;
import com.tma.basicfragment.music.LoadSongTask;
import com.tma.basicfragment.music.Song;
import com.tma.basicfragment.music.SongAdapter;

public class CategoryDetailFragment extends Fragment 
    implements OnCategorySelectedListener {

    static final String TAG = "CategoryDetailFragment";
    static final String KEY_POSITION = "position";

    private int mCurrentPosition = -1;
    private GridView mGridView;

    private Activity mActivity;

    private AsyncTaskCallback<LoadBookResult> mLoadBookTaskCallback = new AsyncTaskCallback<LoadBookResult>() {

        @Override
        public void onTaskCompleted(LoadBookResult result) {
            displayBooks(result.getBooks());

            TaskFragment.detachTask(getFragmentManager());
        }

        @Override
        public void onCancelled() {
            TaskFragment.detachTask(getFragmentManager());
        }
    };

    private AsyncTaskCallback<LoadSongResult> mLoadSongTaskCallback = new AsyncTaskCallback<LoadSongResult>() {

        @Override
        public void onTaskCompleted(LoadSongResult result) {
            displayMusic(result.getSongs());

            TaskFragment.detachTask(getFragmentManager());
        }

        @Override
        public void onCancelled() {

            TaskFragment.detachTask(getFragmentManager());
        }
    };

    @Override
    public void onCategorySelected(int position) {
        mCurrentPosition = position;
        switch (position) {
        case 0:
            if (!TaskFragment.hasAttachedTask(getFragmentManager())) {

                LoadBookTask loadBookTask = new LoadBookTask(mActivity);
                loadBookTask.setCallback(mLoadBookTaskCallback);

                // Attach the task to TaskFragment
                TaskFragment.attachTask(loadBookTask, this, getFragmentManager());

                loadBookTask.execute();
            }
            break;
        case 1:
            if (!TaskFragment.hasAttachedTask(getFragmentManager())) {

                LoadSongTask loadSongTask = new LoadSongTask(mActivity);
                loadSongTask.setCallback(mLoadSongTaskCallback);

                // Attach the task to TaskFragment
                TaskFragment.attachTask(loadSongTask, this, getFragmentManager());

                loadSongTask.execute();
            }
        default:
            break;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AsyncTaskWrapper<?, ?, ?> task = TaskFragment.attachTaskToActivity(mActivity, this, getFragmentManager());
        if (task != null) {
            if (task instanceof LoadBookTask) {
                ((LoadBookTask)task).setCallback(mLoadBookTaskCallback);
            } else if (task instanceof LoadSongTask) {
                ((LoadSongTask)task).setCallback(mLoadSongTaskCallback);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
        }
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.category_detail, container, false);
        mGridView = (GridView) view.findViewById(R.id.gv_list);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point.
        Bundle args = getArguments();
        if (args != null) {
            onCategorySelected(args.getInt(KEY_POSITION));
        } else if (mCurrentPosition != -1) {
            // Load category detail based on saved instance state defined during onCreateView
            onCategorySelected(mCurrentPosition);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TaskFragment.detachTaskFromActivity(getFragmentManager());
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_POSITION, mCurrentPosition);
    }

    public void displayBooks(List<Book> books) {
        if (books == null) {
            return;
        }
        BookAdapter adapter = new BookAdapter(mActivity, books);
        mGridView.setAdapter(adapter);
    }

    public void displayMusic(List<Song> songs) {
        if (songs == null) {
            return;
        }
        SongAdapter adapter = new SongAdapter(mActivity, songs);
        mGridView.setAdapter(adapter);
    }
}
